package com.hqyj.lls.realm;

import com.hqyj.lls.entity.User;
import com.hqyj.lls.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.List;

/**
 * 领域：用于帮我们认证，添加当前主体（subject--用户）的角色信息，权限信息
 *
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Override //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取当前登录的用户
        String username = principalCollection.fromRealm(this.getName()).iterator().next() + "";
        //2.根据用户名查询角色及权限参数
        List<String> roles = userMapper.selectRolesByUsername(username);
        List<String> perms = userMapper.selectPermsByUsername(username);
        //3.获取授权信息对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //4.添加角色信息
        simpleAuthorizationInfo.addRoles(roles);
        //5.添加授权信息
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    @Override //认证 --可研究
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.取出token对象--把AuthenticationToken转换为UsernamePasswordToken
        // (因为AuthenticationToken是把username和password以hash值形式存储)
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        System.out.println("token对象"+token);
        //2.获取身份凭证
        String username = token.getPrincipal()+"";
        System.out.println(username);
        //3.检验是否存在
        User user = userMapper.selectOneByUsername(username);
        //4.判断用户是否存在
        if (user==null){
            throw new UnknownAccountException();
        }
        //new SimpleAuthenticationInfo(用户名，密码，盐值，realm名字)
        return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),this.getName());
    }
}
